package cn.xo68.boot.qrcode;

import cn.xo68.boot.qrcode.properties.QrCodeProperties;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Objects;

/**
 * 二维码生成
 * @author wuxie
 * @version 2019-10-30
 */
@Slf4j
public class QrCodeGenerator {

    private final QrCodeProperties qrCodeProperties;

    public QrCodeGenerator(QrCodeProperties qrCodeProperties) {
        this.qrCodeProperties = qrCodeProperties;
    }

    public QrCodeProperties getQrCodeProperties() {
        return qrCodeProperties;
    }

    /**
     * 覆盖组织logo
     * @param qrImage
     * @param logoImage
     */
    private void drawLogo(BufferedImage qrImage, BufferedImage logoImage){
        int width = qrImage.getWidth();
        int height = qrImage.getHeight();
        // 构建绘图对象
        Graphics2D g = qrImage.createGraphics();
        // 开始绘制logo图片
        int logoWidth=width/qrCodeProperties.getLogoSize().getDenominator();
        int logoHeight=height/qrCodeProperties.getLogoSize().getDenominator();
        int x= (width-logoWidth)/2;
        int y=(height-logoHeight)/2;

        if(qrCodeProperties.isLogoBorder()){
            RoundRectangle2D rectRound = new RoundRectangle2D.Double(x-4,y-4,logoWidth+8,logoHeight+8,8,8);
            g.fill(rectRound);
        }
        g.drawImage(logoImage, x,y,logoWidth,logoHeight, null);
        g.dispose();
        logoImage.flush();
        qrImage.flush();
    }

    /**
     * 生成二维码对象
     * @param width
     * @param height
     * @param margin
     * @param content
     * @return
     */
    private BitMatrix generate(Integer width,Integer height,Integer margin,String content){
        // 定义二维码的配置，使用HashMap
        HashMap hints = new HashMap();
        // 字符集，内容使用的编码
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        // 容错等级，H、L、M、Q
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        // 边距，二维码距离边的空白宽度
        hints.put(EncodeHintType.MARGIN, margin);
        try {
            // 生成二维码对象，传入参数：内容、码的类型、宽高、配置
            BitMatrix bitMatrix =  new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
            return bitMatrix;
        } catch (WriterException e) {
           log.error(e.getMessage(),e);
           return null;
        }
    }

    public BitMatrix generate(String content){
        return generate(qrCodeProperties.getWith(),qrCodeProperties.getHeith(),qrCodeProperties.getMargin(),content);
    }

    public BufferedImage generateAndToBufferedImage(String content){
        BitMatrix bitMatrix =generate(content);
        BufferedImage image = new BufferedImage(bitMatrix.getWidth(), bitMatrix.getHeight(), BufferedImage.TYPE_INT_RGB);

        // 开始利用二维码数据创建Bitmap图片，分别设为黑（0xFFFFFFFF）白（0xFF000000）两色
        for (int x = 0; x < bitMatrix.getWidth(); x++) {
            for (int y = 0; y < bitMatrix.getHeight(); y++) {
                image.setRGB(x, y, bitMatrix.get(x, y) ? qrCodeProperties.getColor() : qrCodeProperties.getBackground());
            }
        }
        image.flush();

        return image;
    }
    public BufferedImage generateAndDrawLogoToBufferedImage(String content, BufferedImage logoImage){
        BufferedImage image=generateAndToBufferedImage(content);
        if (Objects.nonNull(logoImage) ){
            drawLogo(image,logoImage);
        }
        return image;
    }

    /**
     * 生成二维码并保存为文件
     * @param content
     * @param savePath
     */
    public void generateAndWriteFile(String content, Path savePath){
        BitMatrix bitMatrix =generate(content);
        if(bitMatrix!=null){
            try {
                MatrixToImageWriter.writeToPath(bitMatrix, qrCodeProperties.getImageFormat(), savePath);
            } catch (IOException e) {
                log.error(e.getMessage(),e);
            }
        }
    }

    public void generateAndWriteFile(String content, BufferedImage logoImage, Path savePath){
        BufferedImage image=generateAndDrawLogoToBufferedImage(content, logoImage);

        try {
            ImageIO.write(image, qrCodeProperties.getImageFormat(), savePath.toFile());
        } catch (IOException e) {
            throw new QrCodeException(e);
        }
    }
    public void generateAndWriteStream( String content, OutputStream outputStream){
        BitMatrix bitMatrix =generate(content);
        if(bitMatrix!=null){
            try {
                MatrixToImageWriter.writeToStream(bitMatrix, qrCodeProperties.getImageFormat(), outputStream);
            } catch (IOException e) {
                throw new QrCodeException(e);
            }
        }
    }
    public void generateAndWriteStream( String content, BufferedImage logoImage, OutputStream outputStream){
        BufferedImage image=generateAndDrawLogoToBufferedImage(content, logoImage);
        try {
            ImageIO.write(image,qrCodeProperties.getImageFormat(),outputStream);
        } catch (IOException e) {
            throw new QrCodeException(e);
        }
    }
    public byte[] generateAndToBytes(String content, BufferedImage logoImage){
        ByteArrayOutputStream outputStream=new ByteArrayOutputStream(qrCodeProperties.getMaxSize());
        generateAndWriteStream(content,logoImage,outputStream);
        byte[] bytes=outputStream.toByteArray();
        try {
            outputStream.close();
            return bytes;
        } catch (IOException e) {
            log.error(e.getMessage(),e);
            throw new QrCodeException("生成二维码异常");
        }
    }
    public byte[] generateAndToBytes(String content){
        return generateAndToBytes(content,null);
    }


}
